package com.example.service.impl;

import com.example.dao.StudentMapper;
import com.example.model.Student;
import com.example.model.StudentExample;
import com.example.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class StudentServiceImpl implements StudentService {
    @Autowired
    private StudentMapper studentMapper;
    @Override
    public void insertStudent(Student student) {
        studentMapper.insert(student);
    }

    @Override
    public void deleteStudentById(Integer id) {
        studentMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void updateStudent(Student student) {
        studentMapper.updateByPrimaryKeySelective(student);
    }

    @Override
    public Student getStudentById(Integer id) {
        return studentMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Student> listStudents() {
        // 查出全部学生
        // 因为看studentMapper的方法，只能根据主键去操作数据
        // 但是使用example的话就能干更多其他的选择
        // 可以根据学生的学生号或者姓名去查了，我下面在写两个方法吧
        return studentMapper.selectByExample(new StudentExample());
    }

    @Override
    public Student getStudentByStuNo(String stuNo) {
        // 先创建一个example
        StudentExample studentExample = new StudentExample();

        // 这个不知道咋翻译了, 就是里面提供了更加多的一些条件去筛选
        studentExample.createCriteria().andStuNoEqualTo(stuNo);
        // 因为mybatis不知道根据这样查会有多少个对象
        // 所以就返回的是列表了
        List<Student> students = studentMapper.selectByExample(studentExample);
        // 那就再判断一下直接返回第一个就行了
        if (students != null && students.size()!=0){
            return students.get(0);
        }
        // 要是空的直接就返回null把
        return null;
    }

    @Override
    public List<Student> listStudentsByName(String name) {
        StudentExample studentExample = new StudentExample();
        studentExample.createCriteria().andStuNameEqualTo(name);
        // 跟上面一样,还是挺简单的
        return studentMapper.selectByExample(studentExample);
    }
}
